import React, { forwardRef } from 'react';
import { defaultProps } from '../../designer/schema';
import { inbiz } from '@inbiz/core';
import LangProvider from '@inbiz/basic/container';
import zhCN from './locales/zh-CN';
import enUS from './locales/en-US';
import jaJP from './locales/ja-JP';
import View from './components/view';

type IProps = {
  callBackEvents?: {
    onParamFormat?: <T>(param: T) => T;
    onRequest?: (appid: string, params?: any) => Promise<any>;
    onData?: <T>(data: T) => T;
  };
  emit?: {
    /** 自动完成框选中条目时触发 */
    (type: 'onSelect', value?: string, node?: object): void;
    (type: 'onTreeExpand', value?: Array<string>, node?: object): void;
    (type: 'onload'): void;
    (type: 'onError'): void;
    (type: 'onChange', treeData?: Array<string>): void;
    (type: 'onSuccess', treeData?: Array<string>): void;
    (type: any, ...arg: any): void;
  };
  controlId: string;
  onChange?: Function;
  prefixCls?: string;
  className?: string;
  inbiz: inbiz;
  value: any;
  viewMode?:any;
  sourceModel?: string;
  sourcetype?: string;
  selectedKeys?: string[];
  disabled?: boolean;
  readOnly?: boolean;
  title?: string;
  originValue?: string;
  storageConfig?: {
    business: string;
    tableData: {
      componentAttr: string;
      modelAttr: string;
    }[];
  };
} & typeof defaultProps;

const TreeSelect: React.ForwardRefExoticComponent<IProps> &
  IDefaultValueFormat<{ defaultValue: any }> = forwardRef((props, ref: any) => {
  return (
    <LangProvider locales={{ 'zh-CN': zhCN, 'ja-JP': enUS, 'en-US': jaJP }}>
      <View ref={ref} {...props} />
    </LangProvider>
  );
});

//@ts-ignore
TreeSelect['defaultValueFormat'] = (props: IProps) => {
  const selectedId = props?.config?.fieldRelation?.selectedId;
  if (selectedId) {
    if (props.multiple) {
      return selectedId.split(',');
    } else {
      return selectedId;
    }
  } else {
    return undefined;
  }
};
//@ts-ignore
TreeSelect['originValueFormat'] = (value: string | string[], props: IProps) => {
  if (props.multiple) {
    return Array.isArray(value) ? value : value?.split(',');
  } else {
    return value;
  }
};

export default TreeSelect;
export type { IProps };
